from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from app.database.models.chat import ChatSession, ChatMessage
from app.schemas.chat import (
    ChatSessionCreate, ChatSessionUpdate,
    ChatMessageCreate, ChatRequest,
    ChatSession as ChatSessionSchema,  # 导入Pydantic模型
    ChatMessage as ChatMessageSchema
)
from app.config import settings  # 从app.config导入配置
from openai import OpenAI

class ChatService:
    """聊天服务类，处理聊天会话和消息相关业务"""
    # 会话管理方法
    @staticmethod
    def create_chat_session(db: Session, user_id: int, session_in: ChatSessionCreate) -> ChatSession:
        """创建新的聊天会话"""
        db_session = ChatSession(
            user_id=user_id,
            name=session_in.name,
            description=session_in.description
        )
        db.add(db_session)
        db.commit()
        db.refresh(db_session)
        return db_session

    @staticmethod
    def get_chat_sessions(db: Session, user_id: int, skip: int = 0, limit: int = 100) -> list[ChatSession]:
        """获取当前用户的所有会话"""
        return db.query(ChatSession).filter(
            ChatSession.user_id == user_id
        ).offset(skip).limit(limit).order_by(ChatSession.updated_at.desc()).all()

    @staticmethod
    def get_chat_session(db: Session, user_id: int, session_id: int) -> ChatSession:
        """获取特定会话（验证用户权限）"""
        session = db.query(ChatSession).filter(
            ChatSession.id == session_id,
            ChatSession.user_id == user_id
        ).first()

        if not session:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="聊天会话不存在或无权访问"
            )
        return session

    @staticmethod
    def update_chat_session(
            db: Session,
            user_id: int,
            session_id: int,
            session_update: ChatSessionUpdate
    ) -> ChatSession:
        """更新会话信息"""
        session = ChatService.get_chat_session(db, user_id, session_id)
        update_data = session_update.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(session, field, value)
        db.commit()
        db.refresh(session)
        return session

    @staticmethod
    def delete_chat_session(db: Session, user_id: int, session_id: int) -> None:
        """删除会话"""
        session = ChatService.get_chat_session(db, user_id, session_id)
        db.delete(session)
        db.commit()

    # 消息管理方法
    @staticmethod
    def add_message(
            db: Session,
            session_id: int,
            message_in: ChatMessageCreate,
            message_id: str = None
    ) -> ChatMessage:
        """添加消息到会话"""
        db_message = ChatMessage(
            session_id=session_id,
            role=message_in.role,
            content=message_in.content,
            message_id=message_id
        )
        db.add(db_message)
        db.commit()
        db.refresh(db_message)
        return db_message

    @staticmethod
    def get_session_messages(
            db: Session,
            user_id: int,
            session_id: int,
            skip: int = 0,
            limit: int = 100
    ) -> list[ChatMessage]:
        """获取会话的历史消息（验证用户权限）"""
        ChatService.get_chat_session(db, user_id, session_id)
        return db.query(ChatMessage).filter(
            ChatMessage.session_id == session_id
        ).order_by(ChatMessage.created_at.asc()).offset(skip).limit(limit).all()

    # 核心：与豆包AI交互
    @staticmethod
    def chat_with_ai(db: Session, user_id: int, chat_request: ChatRequest) -> tuple[
        ChatSessionSchema, ChatMessageSchema, ChatMessageSchema
    ]:
        """与豆包AI进行聊天，返回序列化后的会话、用户消息、AI消息"""
        # 1. 获取或创建会话
        if chat_request.session_id:
            session = ChatService.get_chat_session(db, user_id, chat_request.session_id)
        else:
            session = ChatService.create_chat_session(
                db,
                user_id,
                ChatSessionCreate(name=chat_request.session_name or "新会话")
            )

        # 2. 保存用户消息（角色为"user"）
        user_message = ChatService.add_message(
            db,
            session.id,
            ChatMessageCreate(role="user", content=chat_request.message)
        )

        # 3. 准备历史上下文
        history_messages = ChatService.get_session_messages(db, user_id, session.id)
        formatted_context = [
            {"role": msg.role, "content": msg.content}
            for msg in history_messages
        ]

        # 4. 调用豆包AI
        try:
            client = OpenAI(
                base_url=settings.DOUBAO_API_BASE_URL,
                api_key=settings.DOUBAO_API_KEY
            )

            response = client.chat.completions.create(
                model=settings.DOUBAO_MODEL,
                messages=formatted_context,
                temperature=0.7
            )

            ai_response_content = response.choices[0].message.content
            if not ai_response_content:
                raise HTTPException(status_code=500, detail="未获取到AI响应内容")

        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"调用豆包AI失败: {str(e)}"
            )

        # 5. 保存AI消息（角色为"ai"，与Pydantic模型匹配）
        ai_message = ChatService.add_message(
            db,
            session.id,
            ChatMessageCreate(role="ai", content=ai_response_content)  # 关键修改：角色改为"ai"
        )

        # 6. 转换为Pydantic模型（解决序列化问题）
        return (
            ChatSessionSchema.from_orm(session),
            ChatMessageSchema.from_orm(user_message),
            ChatMessageSchema.from_orm(ai_message)
        )